package com.huangtang.pc.interceptor;

import com.huangtang.pc.config.ExcludeUrlConfig;
import com.huangtang.pc.constant.CommonConstant;
import com.huangtang.pc.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author sunjf
 * @date 2024/01/05
 */
@Slf4j
@Configuration
public class TestInterceptor implements HandlerInterceptor {


    @Autowired
    private ExcludeUrlConfig excludeUrlConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前访问的uri
        String uri = request.getRequestURI();
        // 获取可以不用授权即可访问的uri
        List<String> urls = excludeUrlConfig.getUrls();

        AntPathMatcher pathMatcher = new AntPathMatcher();

        for (String url : urls) {
            if (pathMatcher.match(url, uri)) {
                log.info("放行uri:{}", uri);
                return true;
            }
        }
        log.info("拦截：{}", uri);

        // TODO 此处做用户鉴权
        String authorization = request.getHeader(CommonConstant.REQUEST_HEADER.AUTHORIZATION);

        if (authorization == null || authorization.isEmpty()) {
            log.info("当前用户信息为空，拦截：{}", request.getRequestURI());
            throw new BizException(401, "当前用户信息为空，请登录后获取令牌重试");
        }


        return true;
    }
}
